import type { RouteRecordRaw } from 'vue-router'
import { clone, omit, searchTree, toTreeArray } from 'xe-utils'
import { useUserStore } from './user'
import { useAppStore } from './app'
import { mapTree } from '@/utils/tree'

export const useRouteStore = defineStore('route', () => {
  const userStore = useUserStore()
  const appStore = useAppStore()

  const initialized = ref(false)
  // 可访问的app路由
  const appRoutes = ref<RouteRecordRaw[]>([])
  const activeRoute = useRoute()
  const activeTopRoute = ref<RouteRecordRaw | undefined>()
  // const activeLeftRoutes = ref<RouteRecordRaw | null>(null)

  watch(() => activeRoute.path, () => {
    // 更新activeTopRoute
    const matchedRoutes = searchTree(appRoutes.value, item => item.path === activeRoute.path)
    const rootPath = matchedRoutes.length ? matchedRoutes[0].path : ''
    activeTopRoute.value = appRoutes.value.find(item => item.path === rootPath)
    // 设置标题
    const names: string[] = [activeRoute.meta.title || '']
    names.push(appStore.website.title)
    document.title = names.join(' - ')
  }, { immediate: true })

  /**
   * 过滤无权限的路由
   */
  function filterAppRoutes(allAppRoutes: RouteRecordRaw[]) {
    return mapTree<RouteRecordRaw, RouteRecordRaw>(allAppRoutes, (item) => {
      if (userStore.hasPermission(item.meta?.code)) {
        return item
      }
    }).filter((item) => {
      if (!item.meta?.hidden && item.children?.length === 0) {
        return false
      }
      return true
    })
  }

  /**
   * 格式化应用路由
   */
  function normalizeAppRoutes(allAppRoutes: RouteRecordRaw[]) {
    // 排序第一级数组
    allAppRoutes?.sort((a, b) => (a.meta?.sort ?? 999) - (b.meta?.sort ?? 999))
    return mapTree<RouteRecordRaw, RouteRecordRaw>(allAppRoutes, (item, index, parent) => {
      // 排序子路由
      item?.children?.sort((a, b) => (a.meta?.sort ?? 999) - (b.meta?.sort ?? 999))
      // 子路由添加parent.path前缀，点击菜单才能正常跳转
      if (parent && !item.path.startsWith('/')) {
        item.path = parent.path.endsWith('/') ? `${parent.path}${item.path}` : `${parent.path}/${item.path}`
      }

      if (item.children) {
        const childrenMenu = item.children.filter(item => !item.meta?.hidden)
        // 如果是目录且所有子路由都没权限，则不显示当前菜单
        if (childrenMenu.length === 0) {
          return
        }
        // 如果子路由只有一条，则redirect到该路由下的第一条页面路由
        // if (childrenMenu.length === 1) {
        item.redirect = `${item.path}/${childrenMenu[0].path}`
        // }
      }
      return item
    })
  }

  // 设置应用路由
  async function setupAppRoutes(allAppRoutes: RouteRecordRaw[]) {
    await userStore.refreshUserInfo()
    const filteredRoutes = filterAppRoutes(allAppRoutes)
    appRoutes.value = normalizeAppRoutes(filteredRoutes)
    const flatRoutes = flatMultiLevelRoutes(filteredRoutes)
    initialized.value = true
    return flatRoutes
  }

  // 判断路由层级是否大于2
  function isMultipleRoute(route: RouteRecordRaw) {
    const children = route.children
    if (children?.length) {
    // 只要有一个子路由的 children 长度大于 0，就说明是三级及其以上路由
      return children.some(child => child.children?.length)
    }
    return false
  }

  // 路由降级（把三级及其以上的路由转化为二级路由
  function flatMultiLevelRoutes(routes: RouteRecordRaw[]) {
    const cloneRoutes = clone(routes, true)
    cloneRoutes.forEach((route) => {
      if (isMultipleRoute(route)) {
        const flatRoutes = toTreeArray(route.children)
        route.children = flatRoutes.map(i => omit(i, ['children'])) as RouteRecordRaw[]
      }
    })
    return cloneRoutes
  }

  return {
    initialized,
    appRoutes,
    activeRoute,
    activeTopRoute,
    setupAppRoutes,
  }
})
